package cn.lzd.zook;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * Created by lzd on 2018/7/24.
 * zookeeper 文件系统的增删改查
 */
public class Zk1 {
    private static String connectString = "hdpn:2181";
    private static int sessionTimeout = 2000;

    private ZooKeeper zkClient = null;

    @Before
    public void init() throws Exception {
        //不设置监听，最后一个参数为null
        zkClient = new ZooKeeper(connectString, sessionTimeout, null);
    }

    @After
    public void end() throws InterruptedException {
        zkClient.close();
    }

    /**
     * 创建子节点
     * 四个参数path, data, acl, createMode
     * path:创建节点的绝对路径
     * data：节点存储的数据
     * acl:权限控制
     * createMode：节点的类型----永久、临时 、有编号的、没有编号的
     */
    @Test
    public void create() throws Exception {
        zkClient.create("/idea", "my idea".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    //判断目录是否存在
    @Test
    public void isExist() {
        try {
            Stat exists = zkClient.exists("/bb0000000001", false);
            System.out.println(exists.getVersion());
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //得到节点数据
    @Test
    public void getData() {
        try {
            byte[] data = zkClient.getData("/bb0000000001", false, null);
            System.out.println(new String(data));
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改节点的数据
     */
    @Test
    public void update() {
        Stat setData = null;
        try {
            setData = zkClient.setData("/bb0000000001", "my bb 2".getBytes(), -1);
            if (setData == null) {
                System.out.println("节点不存在 --- 修改不成功");
            } else {
                System.out.println("节点存在 --- 修改成功");
            }
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    /**
     * 删除节点
     * */
    @Test
    public void delete(){
        try {
            zkClient.delete("/bb0000000001",-1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }
    }

}
